// 这份代码专门处理逻辑层的操作
const punchcardDao = require('../dao/punchcardDao');
const powerDao = require('../dao/powerDao');

const punchcardService = {
    /*
     * 用户签到
     */
    async signIn(uid) {
        let result;
        try {
            result = await punchcardDao.signIn(uid);
            if (result.insertId) {
                result = { success: true, msg: '签到成功' };
            } else {
                result = { success: false, msg: '今日已签到' };
            }
        } catch (err) {
            result = { success: false, msg: "数据库异常" };
        }
        return result;
    },
    /*
     * 检查用户是否已签到
     */
    async checkSigned(uid) {
        let result;
        try {
            result = await punchcardDao.checkSigned(uid);
            if (result[0].signed) {
                result = { success: true, msg: '今日已签到', signed: true };
            } else {
                result = { success: true, msg: '今日未签到', signed: false };
            }
        } catch (err) {
            result = { success: false, msg: "数据库异常" };
        }
        return result;
    },
    /*
     * 查询当月已签到日期
     */
    async getSignedDays(uid) {
        let result;
        try {
            result = await punchcardDao.getSignedDays(uid);
            result = { success: true, msg: '获取当月所有签到日期成功', data: result };
        } catch (err) {
            result = { success: false, msg: "数据库异常" };
        }
        return result;
    },
    /*
     * 获取所有每日打卡记录
     */
    async getPunchcard(uid, page) {
        let result;
        // 鉴权
        try {
            let power = await powerDao.checkPower(uid, '打卡管理');
            if (power.length == 0) {
                result = { success: false, msg: '权限不足' };
                return result;
            }
        } catch (err) {
            result = { success: false, msg: "数据库异常" };
            return result;
        }
        // 业务逻辑
        try {
            result = await punchcardDao.getPunchcard(uid, page);
            result = { success: true, msg: '获取所有打卡记录成功', data: result };
        } catch (err) {
            result = { success: false, msg: "数据库异常" };
        }
        return result;
    }
};

module.exports = punchcardService;